package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.ServerResultVO;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public ServerResultVO<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        String phoneNumber = user.getPhone();
        if (StringUtils.isEmpty(phoneNumber)) {
            return ServerResultVO.error("phone number shouldn't be blank.");
        }

        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //SMSUtils.sendMessage();
        //todo: real phone number and paras
        log.info("validate code:{} for phone:{}", code, phoneNumber);
        request.getSession().setAttribute(phoneNumber, code);
        return ServerResultVO.success("validate number sent.");
    }

    @PostMapping("/login")
    public ServerResultVO<User> login(@RequestBody UserDto userDto, HttpServletRequest request) {
        String phoneNumber = userDto.getPhone();
        if (StringUtils.isEmpty(phoneNumber)) {
            return ServerResultVO.error("phone number shouldn't be blank.");
        }

        String code = userDto.getCode();
        if (!StringUtils.equals((String)request.getSession().getAttribute(phoneNumber), code)) {
            return ServerResultVO.error("wrong phoneNumber or code");
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phoneNumber);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            user = new User();
            user.setPhone(phoneNumber);
            user.setStatus(1);
            userService.save(user);
        }

        request.getSession().setAttribute("user", user.getId());
        return ServerResultVO.success(user);
    }
}
